<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-01-29 17:34:45
 * Desc:
 */

namespace app\api\service;

use app\base\service\BaseService;
use app\base\model\goods\{GoodsBaseInfo,
    GoodsGroupJoinInfo,
    GoodsPlatformInfo,
    GoodsGroupInfo,
    GoodsStatisticsInfo};
use app\base\model\user\{User, UserAccount, UserAccountLog, UserStatisticsInfo};
use app\base\model\system\SystemConfig;
use app\base\model\address\UserPostInfo;
use app\base\model\order\Order;
use app\base\service\Pay\OrderService;
use app\api\service\ShareService;
use app\core\exception\{BusinessException, ErrorCode};
use app\core\cache\{RedisCache, RedisKeys};
use app\core\log\Log4dd;
use think\Db;

class GoodsService extends BaseService
{
    const WISH_NUM_PREFIX = 'XYQ';

    public function __construct()
    {
        RedisCache::selectDB(config('redis_db_index.goods'));
    }

    /**
     * Desc: 获取商品列表
     * Date: 2020/2/28 23:17
     * Author: yiyu
     * @param $user_id
     * @param $page
     * @param $page_size
     * @return array
     */
    public static function getGoodsList($user_id, $page, $page_size)
    {
        return GoodsBaseInfo::apiGetGoodsList($page, $page_size);
    }

    /**
     * Desc: 发起心愿
     * Date: 2020/1/31 16:15
     * Author: yiyu
     * @param $user_id
     * @param $goods_id
     * @param $wish_data
     * @return array
     */
    public static function initiateWish($user_id, $goods_id, $wish_data)
    {

        Log4dd::info('发起心愿,记录请求参数', func_get_args());
        //这里需要记一个redis缓存，防止超卖
        $lock_key = RedisKeys::getGoodsStockLockKey($goods_id);
        if (RedisCache::exists($lock_key)) {
            throw new BusinessException(ErrorCode::COMMON_ERROR, '商品太过火爆，请稍后再试');
        }

        $goods_base_info = GoodsBaseInfo::getGoodsBaseInfo($goods_id);

        if (empty($goods_base_info)) {
            throw new BusinessException(ErrorCode::DATA_NOT_FOUND, '商品不存在');
        }

        if ($goods_base_info['goods_status'] == 0) {
            throw new BusinessException(ErrorCode::DATA_NOT_FOUND, '商品已下架');
        }

        $curr_time = time();

        $open_start_time = strtotime($goods_base_info['open_start_time']);
        $show_start_time = strtotime($goods_base_info['show_start_time']);
        $show_end_time = strtotime($goods_base_info['show_end_time']);

        if ($open_start_time > 0 && $open_start_time < $curr_time) {
            throw new BusinessException(ErrorCode::DATA_NOT_FOUND, '商品即将上架，请耐心等待');
        }

        if ($show_start_time > $curr_time) {
            throw new BusinessException(ErrorCode::DATA_NOT_FOUND, '商品尚未上架1');
        }

        if ($show_end_time > 0 && $show_end_time < $curr_time) {
            throw new BusinessException(ErrorCode::DATA_NOT_FOUND, '商品尚未上架2');
        }

        if ($goods_base_info['goods_stock'] == 0) {
            throw new BusinessException(ErrorCode::COMMON_ERROR, '商品库存不足');
        }

        if ($goods_base_info['goods_stock'] < 5) {
            Log4dd::error('商品库存不足预警', func_get_args());
        }

        if (empty($goods_base_info['need_wish_coin']) || $goods_base_info['need_wish_coin'] < 0) {
            Log4dd::error('商品发起兑换需要的心愿币数量配置为0，商品id：' . $goods_id, func_get_args());
            throw new BusinessException(ErrorCode::COMMON_ERROR, '商品配置有误1');
        }

        if ($goods_base_info['need_wish_coin'] < 5) {
            Log4dd::error('商品发起兑换需要的心愿币数量<5，商品id：' . $goods_id, func_get_args());
        }

        if (empty($goods_base_info['need_people'])) {
            Log4dd::error('商品拼团需要参与的人数配置为0，商品id：' . $goods_id, func_get_args());
            throw new BusinessException(ErrorCode::COMMON_ERROR, '商品配置有误2');
        }

        if (empty($goods_base_info['people_get_wish_coin'])) {
            Log4dd::error('商品拼团参与的用户每人支付后可获得的心愿币数量为0，商品id：' . $goods_id, func_get_args());
            throw new BusinessException(ErrorCode::COMMON_ERROR, '商品配置有误3');
        }

        while (RedisCache::setNx($lock_key, 1)) {
            usleep(50000);
        }
        RedisCache::expire($lock_key, 2);

        $wish_coin_num = UserAccount::getWishCoinNumByUserId($user_id);

        if ($wish_coin_num < $goods_base_info['need_wish_coin']) {
            throw new BusinessException(ErrorCode::CURRENCY_NOT_ENOUGH, '心愿值还不够哦');
        }

        if (empty($goods_base_info['platform_price']) || $goods_base_info['platform_price'] < 0) {
            Log4dd::error('商品拼团第三方平台价格配置有误，商品id：' . $goods_id, func_get_args());
            throw new BusinessException(ErrorCode::COMMON_ERROR, '商品配置有误5');
        }

        if ($goods_base_info['platform_price'] < 5) {
            Log4dd::error('商品拼团第三方平台价格<5元，商品id：' . $goods_id, func_get_args());
        }


        Db::startTrans();

        try {
            //先扣除库存
            $res = GoodsBaseInfo::where('goods_id', $goods_id)->setDec('goods_stock');
            if (!$res) {
                Db::rollback();
                throw new BusinessException('更新库存失败');
            }

            //扣款
            $operation_res = UserAccount::operationUserAccount($user_id, $user_id, UserAccount::WISH_COIN,
                $goods_base_info['need_wish_coin'] * -1, 'initiate_wish', '发起了 <span style="color: #333333;font-weight: bold;">' . $goods_base_info['goods_name'] . '</span> 心愿', 0);

            if (!isset($operation_res['err_num']) || $operation_res['err_num'] != 0) {
                Db::rollback();
                throw new BusinessException('扣除心愿值失败');
            }

            $can_free_support = $goods_base_info['can_free'] ?? 0;

            //保存发起信息
            $group_info = [
                'goods_id' => $goods_id,
                'user_id' => $user_id,
                'my_wish' => $wish_data['my_wish'] ?? '',
                'need_people' => $goods_base_info['need_people'],
                'need_wish_coin' => $goods_base_info['need_wish_coin'],
                'group_total_price' => $goods_base_info['platform_price'],
                'group_state' => 1,
                'can_free_support' => $can_free_support ? 1 : 0,//是否可以首次免费支持
                'create_time' => date('Y-m-d H:i:s')
            ];

            $group_model = GoodsGroupInfo::create($group_info);

            if (!$group_model->group_id) {
                Db::rollback();
                throw new BusinessException('发起拼团失败');
            }

            $group_id = $group_model->group_id;

            UserAccountLog::where('log_id', $operation_res['log_id'])->update(['group_id' => $group_id]);
            //更新发起次数
            GoodsStatisticsInfo::GoodsStatistics($goods_id, 'initiate_num', 1);


            Db::commit();
            RedisCache::del($lock_key);
            GoodsBaseInfo::delGoodsInfoCache($goods_id);

            //需要发送异步消息，发起心愿成功

            $group_info['need_pay_money'] = self::calculateNeedPayMoney($group_info);

            return array_merge($group_info, ['group_id' => $group_id]);

        } catch (BusinessException $e) {
            Db::rollback();
            Log4dd::info("发起心愿失败:{$e->getMessage()}", func_get_args(), $e);
            throw new BusinessException($e->getCode(), $e->getMessage());
        }


    }

    /**
     * Desc: 取消心愿
     * Date: 2020/2/28 23:17
     * Author: yiyu
     * @param $user_id
     * @param $group_id
     * @param bool $is_admin
     * @return bool
     */
    public static function cancelWish($user_id, $group_id, $is_admin = false)
    {

        Log4dd::info('取消心愿service层请求参数1', func_get_args());

        $group_info = GoodsGroupInfo::find($group_id);

        if (empty($group_info)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '要取消的心愿不存在');
        }

        $goods_base_info = GoodsBaseInfo::getGoodsBaseInfo($group_info['goods_id']);

        if (empty($goods_base_info)) {
            throw new BusinessException(ErrorCode::DATA_NOT_FOUND, '商品不存在');
        }

        $group_info = GoodsGroupInfo::find($group_id);

        Log4dd::info('取消心愿service层请求参数2', ['user_id' => $user_id, 'group_id' => $group_id, 'group_info' => $group_info]);

        if (empty($group_info)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '要取消的心愿不存在');
        }

        if (!$is_admin && $user_id != $group_info['user_id']) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '拒绝操作');
        }

        if ($group_info['join_people'] > 0) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '该心愿已有人支持，不能取消');
        }

        if ($group_info['group_state'] != GoodsGroupInfo::GROUP_RUN_STATE) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '该心愿当前状态不能取消');
        }

        if ($group_info['group_state'] == GoodsGroupInfo::GROUP_CANCEL_STATE) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '已取消，不能重复取消');
        }

        if ($is_admin) {
            $account_type = User::getUserFieldById($group_info['user_id'], 'account_type');
            if ($account_type != User::ACCOUNT_TYPE_ROBOT) {
                throw new BusinessException(ErrorCode::COMMON_ERROR, '只能取消机器人心愿');
            }
        }

        Db::startTrans();

        try {
            $ret = GoodsGroupInfo::where('group_id', $group_id)->update([
                'group_state' => $is_admin ? GoodsGroupInfo::GROUP_ADMIN_CANCEL_STATE : GoodsGroupInfo::GROUP_CANCEL_STATE,
                'cancel_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s')
            ]);

            if ($ret) {

                //获取用户发起心愿时扣除的心愿值
                $operation_number = UserAccountLog::where('user_id', $group_info['user_id'])->where('group_id', $group_id)->where('operation_type', 'initiate_wish')->where('account_type', UserAccount::getLogAccountType(UserAccount::WISH_COIN))->value('operation_number');
                Log4dd::info('取消心愿，获取用户发起心愿时扣除的心愿值', ['user_id' => $group_info['user_id'], 'group_id' => $group_id, 'group_info' => $group_info, 'sql' => UserAccountLog::getLastSql()]);
                if (empty($operation_number)) {
                    Log4dd::error('用户取消心愿,未找到扣除的心愿值记录', ['user_id' => $group_info['user_id'], 'group_id' => $group_id]);
                    Db::rollback();
                    throw new BusinessException(ErrorCode::DATA_NOT_FOUND, '取消失败，请稍后再试！');
                }

                $operation_type = $is_admin ? 'admin_cancel_wish' : 'cancel_wish';

                //返还心愿值
                $operation_res = UserAccount::operationUserAccount($group_info['user_id'], $user_id, UserAccount::WISH_COIN,
                    $operation_number * -1, $operation_type, '取消了 <span style="color: #333333;font-weight: bold;">' . $goods_base_info['goods_name'] . '</span> 心愿', $group_id);

                Log4dd::info('取消心愿，返还心愿值', ['user_id' => $group_info['user_id'], 'group_id' => $group_id, 'group_info' => $group_info, 'operation_number' => $operation_number, 'operation_res' => $operation_res]);

                if (!isset($operation_res['err_num']) || $operation_res['err_num'] != 0) {
                    Db::rollback();
                    throw new BusinessException(ErrorCode::COMMON_ERROR, '操作失败，请稍后重试！');
                }

                //返还库存
                GoodsBaseInfo::where('goods_id', $group_info['goods_id'])->setInc('goods_stock');

                GoodsBaseInfo::delGoodsInfoCache($group_info['goods_id']);

                Db::commit();

                return true;
            }
        } catch (BusinessException $e) {
            Db::rollback();
            Log4dd::info("取消心愿失败:{$e->getMessage()}", func_get_args(), $e);
            throw new BusinessException($e->getCode(), $e->getMessage());
        }
    }

    /**
     * Desc: 支持别人的心愿，分为用户主动支持和机器人支持
     * Date: 2020/1/31 20:49
     * Author: yiyu
     * @param $user_id
     * @param $account_type
     * @param $group_ids
     * @param $params
     * @return array
     */
    public static function supportWish($user_id, $account_type, $group_ids, $params)
    {
        Log4dd::info('支持TA人心愿,记录请求参数', func_get_args());

        if (!isset($params['pay_way']) || empty($params['pay_way'])) {
            throw new BusinessException(ErrorCode::COMMON_ERROR, '支付渠道pay_way未传');
        }

        if (!isset($params['pay_mode']) || empty($params['pay_mode'])) {
            throw new BusinessException(ErrorCode::COMMON_ERROR, '支付方式pay_mode未传');
        }


        if (empty($group_ids) || !is_array($group_ids)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '要支持的信息不存在');
        }

        $group_items = GoodsGroupInfo::field('group_id,goods_id,user_id,need_people,join_people,group_state,group_total_price,group_curr_pay_price,can_free_support')
            ->whereIn('group_id', $group_ids)
            ->where('user_id', '<>', $user_id)
            ->where('group_state', GoodsGroupInfo::GROUP_RUN_STATE)
            ->whereExp('need_people', '>join_people')
            ->whereExp('group_total_price', '>group_curr_pay_price')
            ->select();

        Log4dd::info('支持TA人心愿,记录请求参数2', [func_get_args(), $group_items]);

        if (count($group_ids) != count($group_items)) {
            throw new BusinessException(ErrorCode::DATA_NOT_FOUND, '信息已更新，请刷新后再试');
        }

        try {
            $order_money = $pay_money = 0;
            $group_goods_info = [];

            $order_remark = '支持group_id为 [';

            $can_free_support = false;

            $had_support = GoodsGroupJoinInfo::hadSupport($user_id);
            //获取总计应付款金额
            foreach ($group_items as $item) {
                $need_pay_money = self::calculateNeedPayMoney($item);
                if (false == $can_free_support && $item['can_free_support'] == 1 && false == $had_support) {
                    $is_free = 1;
                    $can_free_support = true;
                    $pay_money += 0.00;
                } else {
                    $is_free = 0;
                    $pay_money += $need_pay_money;
                }
                $order_money += $need_pay_money;
                $group_goods_info[] = [
                    'user_id' => $item['user_id'],
                    'group_id' => $item['group_id'],
                    'goods_id' => $item['goods_id'],
                    'pay_money' => $is_free ? '0.00' : $need_pay_money,
                    'get_gold_num' => self::calculateCanGetWishCoinNum($need_pay_money),
                    'free_support' => $is_free
                ];
                $order_remark .= $item['group_id'] . ',';
            }

            $order_remark = rtrim($order_remark, ',');

            Log4dd::info('支持TA人心愿,记录请求参数3', [func_get_args(), $group_goods_info]);

            if (empty($group_goods_info) || !is_array($group_goods_info)) {
                throw new BusinessException(ErrorCode::COMMON_ERROR, 'group_ids参数无效');
            }

            $order_remark .= ']的心愿';

            $base_info = [
                'pay_way' => $params['pay_way'],
                'pay_mode' => $params['pay_mode'],
                'app_id' => $params['app_id'] ?? '',
                'order_money' => $order_money,
                'pay_money' => $account_type == User::ACCOUNT_TYPE_ROBOT ? '0.00' : $pay_money,
                'is_robot' => $account_type == User::ACCOUNT_TYPE_ROBOT ? 1 : 0,
                'order_remark' => $order_remark,
            ];

            return OrderService::instance()->createSystemNewOrder($user_id, $group_goods_info, $base_info);//先在本地系统创建订单

        } catch (BusinessException $e) {
            Log4dd::info("支持TA人心愿，本地创建订单失败:{$e->getMessage()}", func_get_args(), $e);
            throw new BusinessException(ErrorCode::COMMON_ERROR, '下单失败');
        }


    }

    public static function freeSupportWish($user_id, $group_id)
    {

        if (empty($group_ids) || is_array($group_ids)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '要支持的信息不存在');
        }

        try {

        } catch (BusinessException $e) {
            Log4dd::info("免费支持支持TA人心愿，支持失败:{$e->getMessage()}", func_get_args(), $e);
            throw new BusinessException(ErrorCode::COMMON_ERROR, '下单失败');
        }


    }

    /**
     * Desc: 计算支持心愿需要付款的金额，保留一位小数
     * Date: 2020/2/16 22:23
     * Author: yiyu
     * @param $group
     * @return float|int
     */
    public static function calculateNeedPayMoney($group)
    {
        if (!isset($group['group_total_price'], $group['need_people'])) {
            return 0;
        }

        $need_pay_money = $group['group_total_price'] / $group['need_people'];

        //保留一位小数
        if (is_float($need_pay_money)) {
            $need_pay_money = self::checkDecimals($need_pay_money, 'floor', 100);
        }

        return $need_pay_money;

    }

    /**
     * Desc: 计算支持心愿课获得的心愿值，保留一位小数（可获得的心愿值 = 支付的金额 * 心愿值赠送比率）
     * Date: 2020/2/16 22:24
     * Author: yiyu
     * @param $money
     * @return float|int
     */
    public static function calculateCanGetWishCoinNum($money)
    {
        $default_gold_give_ratio = self::getDefaultGoldGiveRatio();
        $wish_coin = $default_gold_give_ratio * $money;

        if (is_float($wish_coin)) {
            $wish_coin = self::checkDecimals($wish_coin, 'ceil');
        }

        return $wish_coin;

    }


    /**
     * Desc: 处理小数
     * Date: 2020/2/28 23:18
     * Author: yiyu
     * @param $number
     * @param $fun
     * @param $num
     * @return float|int
     */
    public static function checkDecimals($number, $fun, $num = 10)
    {
        if ($fun == 'ceil') {
            return (float)(ceil($number * $num)) / $num;
        }

        if ($fun == 'floor') {
            return (float)(floor($number * $num)) / $num;
        }

        return (float)(($number * $num)) / $num;

    }

    /**
     * Desc: 获取系统默认的心愿值赠送比率
     * Date: 2020/2/16 22:24
     * Author: yiyu
     * @return bool|string
     */
    public static function getDefaultGoldGiveRatio()
    {
        return SystemConfig::getSystemConfigByName('default_wish_coin_give_ratio',
            config('goods_default_config.default_wish_coin_give_ratio'));
    }

    /**
     * Desc: 首次支持额外赠送心愿值数量
     * Date: 2020/2/16 22:42
     * Author: yiyu
     * @return bool|string
     */
    public static function getFirstSupportWishGiveWishCoinNum()
    {
        return SystemConfig::getSystemConfigByName('new_user_first_support_extra_give', 0);
    }

    /**
     * Desc: 获取心愿详情
     * Date: 2020/2/3 22:16
     * Author: yiyu
     * @param $user_id
     * @param $group_id
     * @return mixed
     */
    public static function getWishInfo($user_id, $group_id)
    {
        $data = GoodsGroupInfo::find($group_id);
        $goods_base_info = GoodsBaseInfo::getGoodsBaseInfo($data['goods_id']);
        $user_info = User::getUserInfoById($data['user_id'], ['nick_name', 'gender', 'small_avatar_url']);

        $result['user_id'] = $data['user_id'];
        $result['nick_name'] = $user_info['nick_name'] ?? '';
        $result['gender'] = $user_info['gender'] ?? 1;
        $result['avatar_url'] = $user_info['small_avatar_url'] ?? '';
        $result['need_people'] = $data['need_people'];
        $result['join_people'] = $data['join_people'];
        $diff_people = $result['need_people'] - $result['join_people'];
        $result['diff_people'] = $diff_people >= 0 ? $diff_people : 0;
        $result['group_state'] = $data['group_state'];
        $result['goods_id'] = $data['goods_id'];
        $result['need_pay_money'] = self::calculateNeedPayMoney($data);
        $result['platform_price'] = $data['group_total_price'];
        $result['platform_name'] = $goods_base_info['platform_name'];
        $result['get_wish_coin'] = $goods_base_info['people_get_wish_coin'];
        $result['goods_name'] = $goods_base_info['goods_name'];
        $result['goods_img_url'] = $goods_base_info['goods_img_url'];

        $result['can_support'] = $data['group_state'] == GoodsGroupInfo::GROUP_RUN_STATE ? 1 : 0;//是否可以继续支持
        //判断自己是否已支持
        $join_info = GoodsGroupJoinInfo::getGroupJoinUserInfoByUserId($group_id, $user_id);
        $join_info && $result['can_support'] = 0;
        $result['i_had_support'] = $join_info ? 1 : 0;
        $result['is_me'] = ($data['user_id'] == $user_id ? 1 : 0);
        $result['is_free'] = $data['can_free_support'] ?? 0;
        $result['can_free_support'] = ($data['can_free_support'] == 1 && false == GoodsGroupJoinInfo::hadSupport($user_id)) ? 1 : 0;//是否可以免费支持

        $result['wish_introduce_long_img_url'] = SystemConfig::getSystemConfigByName('wish_introduce_long_img_url', '');
        $result['share_info'] = ShareService::instance()->miniProgramShareWish($group_id, $data['goods_id'], $data['user_id']);

        return $result;
    }

    /**
     * Desc: 心愿详情按钮文案
     * Date: 2020/2/22 23:52
     * Author: yiyu
     * @return array
     */
    public static function getWishDetailInfoButtonText()
    {
        $button_share = SystemConfig::getSystemConfigByName('wish_detail_invite_share_button', '邀请好友支持');
        $button_initiate = SystemConfig::getSystemConfigByName('wish_detail_initiate_wish_button', '去发起新的心愿');
        $button_support = SystemConfig::getSystemConfigByName('wish_detail_support_wish_button', '立即支持TA');
        $button_i_initiate = SystemConfig::getSystemConfigByName('wish_detail_i_initiate_wish_button', '我也要发起心愿');
        $wish_detail_button_bubble_tips = SystemConfig::getSystemConfigByName('wish_detail_button_bubble_tips', '<p><span style="color: #f8e71c;">免费<span style="color: #ffffff;">支持</span></span></p>');
        $wish_detail_bubble_tips = SystemConfig::getSystemConfigByName('wish_detail_bubble_tips', '<p><span style="color: #ffffff;">新用户</span><span style="color: #f8e71c;">免费<span style="color: #ffffff;">支持</span></span></p>');
        return compact('button_share', 'button_initiate', 'button_support', 'button_i_initiate', 'wish_detail_button_bubble_tips', 'wish_detail_bubble_tips');
    }

    /**
     * Desc: 将心愿和收货地址绑定
     * Date: 2020/2/3 22:15
     * Author: yiyu
     * @param $user_id
     * @param $group_id
     * @param int $address_id
     * @param string $address_info
     * @return UserPostInfo
     */
    public static function bindAddress($user_id, $group_id, $address_id = 0, $address_info = '')
    {
        $info = UserPostInfo::where('user_id', $user_id)->where('group_id', $group_id)->find();

        if (empty($address_id) && empty($address_info)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '地址id和地址信息不能同时为空');
        }

        if ($info) {
            $address_id && $data['address_id'] = $address_id;
            $address_info && $data['address_info'] = $address_info;
            $data['update_time'] = date('Y-m-d H:i:s');
            $res = UserPostInfo::where('log_id', $info['log_id'])->update($data);
        } else {

            $data = [
                'user_id' => $user_id,
                'group_id' => $group_id,
                'create_time' => date('Y-m-d H:i:s')
            ];

            $address_id && $data['address_id'] = $address_id;
            $address_info && $data['address_info'] = $address_info;

            $res = UserPostInfo::create($data);
        }

        return $res;
    }

    /**
     * Desc: 添加访问记录，同一个用户1小时同一个商品只记录一次
     * Date: 2020/2/3 22:15
     * Author: yiyu
     * @param $user_id
     * @param $goods_id
     * @return bool
     */
    public static function addVisitLog($user_id, $goods_id)
    {

        $key = RedisKeys::getGoodsVisitKey($user_id, $goods_id);

        if (RedisCache::exists($key)) {
            return false;
        }

        GoodsStatisticsInfo::GoodsStatistics($goods_id, 'visit_num', 1);

        RedisCache::set($key, 1, 3600);

        return true;

    }

    /**
     * Desc: 支持别人的心愿可以获得的奖励信息
     * （推荐的商品列表）
     * 适用于：
     * 1、首页-支持他人弹窗 点击【支持 TA】按钮后弹出
     * 2、兑换-好物兑换-支持他人弹窗 点击【立即支持】按钮后弹出
     * 3、心愿详情-支持他人弹窗 点击【立即支持 TA】后弹出
     * Date: 2020/2/16 23:12
     * Author: yiyu
     * @param int $user_id
     * @param float $base_wish_coin
     * @param array $group_info
     * @param string $currency_name
     * @return array
     */
    public static function SupportWishRewardInfo($user_id, $base_wish_coin = 0, $group_info = [], $currency_name = '')
    {
        //判断用户的属性，参数由后台配置
        //用户为首次支持 [本次需支付的价格>= 10 多得20心愿值， 本次需支付的价格<10,获得3倍的心愿值]
        //用户非第一次支持 [获得和价格等额的心愿值]

        //$statistics_info = UserStatisticsInfo::find($user_id);
        $had_support = GoodsGroupJoinInfo::hadSupport($user_id);


        $give_ratio = self::getDefaultGoldGiveRatio();

        //$price_dividing = SystemConfig::getSystemConfigByName('new_user_price_dividing', 10);

        //$plan_a = SystemConfig::getSystemConfigByName('new_user_first_support_extra_times', 3);

        $extra_give = self::getFirstSupportWishGiveWishCoinNum();

        $is_first = 0;//是否首次 0 不是 1是

        $is_free = 0;

        $i_can_get_text = '';

        empty($currency_name) && $currency_name = SystemConfig::getSystemConfigByName('sys_currency_name', config('sys_currency_name'));
        //未付过款的情况下
        if (false == $had_support && $group_info && isset($group_info['can_free_support']) && $group_info['can_free_support'] == 1) {
            /*if ($base_wish_coin < $price_dividing) {
                $wish_coin_num = round($base_wish_coin * $plan_a, 1);
                $wish_coin_text = '首次帮TA达成心愿·你可获得' . $plan_a . '倍' . $currency_name;
                $top_left_icon = $plan_a_icon;
            }*/

            $wish_coin_num = $base_wish_coin;

            //if ($base_wish_coin >= $price_dividing) {
            $wish_coin_text = '首次支持他人心愿·你多得<span style="color: #E7404A;">' . $extra_give . $currency_name . '</span>';
            //$top_left_icon = SystemConfig::getSystemConfigByName('first_support_top_left_icon', '');
            //}
            $top_left_icon = SystemConfig::getSystemConfigByName('first_free_support_top_left_icon', '');
            $is_first = 1;
            $is_free = 1;
            if ($extra_give) {
                $i_can_get_text = '我得' . $base_wish_coin . '+' . $extra_give . '=' . $wish_coin_num . $currency_name;
            } else {
                $i_can_get_text = '我得' . $base_wish_coin . $currency_name;
            }
        } else {
            $extra_give = 0;
            $need_money = self::calculateNeedPayMoney($group_info);
            $wish_coin_num = self::calculateCanGetWishCoinNum($need_money);
            $wish_coin_num = self::checkDecimals($wish_coin_num, 'ceil');
            if ($give_ratio == 1) {
                $wish_coin_text = '支持他人心愿·你得<span style="color: #E7404A;">等额' . $currency_name . '</span>';
            } else {
                $wish_coin_text = '支持他人心愿·你得<span style="color: #E7404A;">' . $give_ratio . '倍' . $currency_name . '</span>';
            }
            //这里比较巧妙，有group_info的时候刚好有值，没有group_info的时候客户端又不需要i_can_get_text这个字段
            $need_money && $i_can_get_text = '我得' . $need_money . 'x' . $give_ratio . '=' . $wish_coin_num . $currency_name;
            $top_left_icon = '';
        }

        $my_wish_coin_num = UserAccount::getWishCoinNumByUserId($user_id);//支付前账户的心愿值

        $goods_list = self::getRecommendGoodsInfos($user_id, $my_wish_coin_num);

        $payed_wish_coin_num = $my_wish_coin_num + $wish_coin_num;//支付后账户的心愿值
        $recommend_goods_info = self::getGoodsByWishValue(($my_wish_coin_num + $wish_coin_num));
        $wish_coin_enough = 0;
        if ($recommend_goods_info) {
            $wish_coin_enough = $recommend_goods_info['need_wish_coin'] >= $payed_wish_coin_num ? 0 : 1;
        }

        return compact('wish_coin_num', 'payed_wish_coin_num', 'wish_coin_text', 'top_left_icon', 'i_can_get_text', 'is_first', 'is_free', 'extra_give', 'give_ratio', 'goods_list', 'recommend_goods_info', 'wish_coin_enough');
    }

    /**
     * Desc: 获取推荐的商品id列表
     * Date: 2020/2/19 13:09
     * Author: yiyu
     * @param $user_id
     * @return array
     */
    public static function getRecommendGoodsIds($user_id)
    {
        //判断用户是否付费
        $is_pay = Order::hasPay($user_id);

        if ($is_pay) {
            //付费用户展示所有已上架商品中的三个
            $ids = GoodsBaseInfo::getRecommendGoodsIds();
        } else {
            $ids = GoodsBaseInfo::getRecommendGoodsIds(['gb.need_wish_coin' => ['<', 50]]);
        }

        if ($ids) {
            shuffle($ids);
            return array_slice($ids, 0, 3);
        } else {
            $ids_str = SystemConfig::getSystemConfigByName('recommend_goods_ids', '');
            return array_filter(array_map('intval', explode(',', $ids_str)));
        }

    }


    public static function getRecommendGoodsInfos($user_id, $my_wish_coin_num, $limit = 3)
    {

        $goods_list = GoodsBaseInfo::getMultipleGoodsByWishValue($my_wish_coin_num, $limit);

        return $goods_list;
    }


    public static function getGoodsByWishValue($wish_value)
    {
        return GoodsBaseInfo::getOneGoodsByWishValue($wish_value);

    }


}